// 弹窗组件
import { Radio, Modal, Form, Input, Row, Col, Button, Checkbox, message } from 'antd';
import styles from "../css/LoginForm.module.scss"
import { useState, useRef, useEffect } from 'react';
import { getCaptcha, userIsExist, addUser, userLogin, getUserById } from "../api/user"
import { initUserInfo, changeUserStatus } from "../redux/userSlice";
import { useDispatch } from 'react-redux';

interface IProps {
    isShow: boolean,
    closeModal: () => void
}
interface ILoginInfo {
    loginId: string,
    nickname?: string,
    captcha?: string,
    remember?: boolean,
}

function LoginForm(props: IProps) {
    const registerFormRef = useRef(null)
    const loginFormRef = useRef(null)
    const [value, setValue] = useState(1)
    const [captcha, setCaptcha] = useState("");
    const dispatch = useDispatch()
    // 注册表单的状态数据
    const [registerInfo, setRegisterInfo] = useState({
        loginId: "",
        nickname: "",
        captcha: "",
    })
    // 登录表单的状态数据
    const [loginInfo, setLoginInfo] = useState({
        loginId: "",
        loginPwd: "",
        captcha: "",
        remember: false
    });
    const fetchData = async () => {
        const res = await getCaptcha();
        setCaptcha(res.data)
    }
    useEffect(() => {
        fetchData()
    }, [])

    const updateInfo = (oldInfo: ILoginInfo, newContent: any, key: string, setInfo: any) => {
        const obj: any = { ...oldInfo }
        obj[key] = newContent;
        setInfo(obj)
    }
    const onChange = (e: any) => {
        setValue(e.target.value)
        fetchData()
    }
    // 关闭弹窗
    const handleCancel = () => {
        hanldeReset()
        props.closeModal();
    }
    // 重置
    const hanldeReset = () => {
        const remember = loginInfo.remember;
        // 清空上次内容
        (loginFormRef.current as any)?.resetFields();
        (registerFormRef.current as any)?.resetFields();
        setLoginInfo({
            loginId: "",
            loginPwd: "",
            captcha: "",
            remember
        })
        setRegisterInfo({
            loginId: "",
            nickname: "",
            captcha: "",
        })
    }
    // 注册完成
    const registerHandle = async () => {
        const { data } = await addUser(registerInfo);
        if (data.data) {
            // 注册成功
            message.success("用户注册成功，默认密码为123456")
            // 将用户信息存储数据仓库
            dispatch(initUserInfo(data.data));
            dispatch(changeUserStatus(true));
            handleCancel();
        } else {
            // 注册失败
            message.warning(data.msg)
            fetchData()
        }
    }
    const loginHandle = async () => {
        const { data } = await userLogin(loginInfo);
        if (data.data) {
            // 验证码正确
            const res = data.data
            if (!res.data) {
                // 账号密码不正确
                message.error("账号密码不正确")
            } else if (!res.data.enabled) {
                // 账户被冻结
                message.warning("此账户被冻结")
            } else {
                // 登录成功，存储token
                localStorage.setItem('token', res.token)
                // 存储用户信息
                const result = await getUserById(res.data._id)
                const userInfo = result.data.data;
                dispatch(initUserInfo(userInfo));
                // 修改登录状态
                dispatch(changeUserStatus(true));
                handleCancel()
            }
        } else {
            message.warning(data.msg)
            fetchData();
        }
    }
    const captchaClickHandle = () => {
        fetchData()
    }

    // 验证登录账号是否存在
    const checkLoginIdIsExist = async () => {
        if (registerInfo.loginId) {
            const { data } = await userIsExist(registerInfo.loginId);
            if (data.data) {
                // 该id已经被注册
                return Promise.reject("该用户已存在")
            }
        }
    }
    let container;
    if (value === 1) {
        // 登录
        container = (
            <div className={styles.container}>
                <Form
                    name="basic1"
                    autoComplete="off"
                    onFinish={loginHandle}
                    ref={loginFormRef}
                >
                    <Form.Item
                        label="登录账号"
                        name="loginId"
                        rules={[
                            {
                                required: true,
                                message: "请输入账号",
                            },
                        ]}
                    >
                        <Input
                            placeholder="请输入你的登录账号"
                            value={loginInfo.loginId}
                            onChange={(e) => updateInfo(loginInfo, e.target.value, 'loginId', setLoginInfo)}
                        />
                    </Form.Item>

                    <Form.Item
                        label="登录密码"
                        name="loginPwd"
                        rules={[
                            {
                                required: true,
                                message: "请输入密码",
                            },
                        ]}
                    >
                        <Input.Password
                            placeholder="请输入你的登录密码，新用户默认为123456"
                            value={loginInfo.loginPwd}
                            onChange={(e) => updateInfo(loginInfo, e.target.value, 'loginPwd', setLoginInfo)}
                        />
                    </Form.Item>

                    {/* 验证码 */}
                    <Form.Item
                        name="logincaptcha"
                        label="验证码"
                        rules={[
                            {
                                required: true,
                                message: '请输入验证码',
                            },
                        ]}
                    >
                        <Row align="middle">
                            <Col span={16}>
                                <Input
                                    placeholder="请输入验证码"
                                    value={loginInfo.captcha}
                                    onChange={(e) => updateInfo(loginInfo, e.target.value, 'captcha', setLoginInfo)}
                                />
                            </Col>
                            <Col span={6}>
                                <div
                                    className={styles.captchaImg}
                                    onClick={captchaClickHandle}
                                    dangerouslySetInnerHTML={{ __html: captcha }}
                                ></div>
                            </Col>
                        </Row>
                    </Form.Item>

                    <Form.Item
                        name="remember"
                        wrapperCol={{
                            offset: 5,
                            span: 16,
                        }}
                    >
                        <Checkbox
                            onChange={(e) => updateInfo(loginInfo, e.target.checked, 'remember', setLoginInfo)}
                            checked={loginInfo.remember}
                        >记住我</Checkbox>
                    </Form.Item>

                    <Form.Item
                        wrapperCol={{
                            offset: 5,
                            span: 16,
                        }}
                    >
                        <Button
                            type="primary"
                            htmlType="submit"
                            style={{ marginRight: 20 }}
                        >
                            登录
                        </Button>
                        <Button type="primary" htmlType="button" onClick={hanldeReset}>
                            重置
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        )
    } else {
        // 注册
        container = (
            <div className={styles.container}>
                <Form
                    name="basic2"
                    autoComplete="off"
                    ref={registerFormRef}
                    onFinish={registerHandle}
                >
                    <Form.Item
                        label="登录账号"
                        name="loginId2"
                        rules={[
                            {
                                required: true,
                                message: "请输入账号，仅此项为必填项",
                            },
                            // 验证用户是否已经存在
                            { validator: checkLoginIdIsExist },
                        ]}
                        validateTrigger='onBlur'
                    >
                        <Input
                            placeholder="请输入账号"
                            value={registerInfo.loginId}
                            onChange={(e) => updateInfo(registerInfo, e.target.value, 'loginId', setRegisterInfo)}
                        />
                    </Form.Item>

                    <Form.Item
                        label="用户昵称"
                        name="nickname"
                    >
                        <Input
                            placeholder="请输入昵称，不填写默认为新用户xxx"
                            value={registerInfo.nickname}
                            onChange={(e) => updateInfo(registerInfo, e.target.value, 'nickname', setRegisterInfo)}
                        />
                    </Form.Item>

                    <Form.Item
                        name="registercaptcha"
                        label="验证码"
                        rules={[
                            {
                                required: true,
                                message: '请输入验证码',
                            },
                        ]}
                    >
                        <Row align="middle">
                            <Col span={16}>
                                <Input
                                    placeholder="请输入验证码"
                                    value={registerInfo.captcha}
                                    onChange={(e) => updateInfo(registerInfo, e.target.value, 'captcha', setRegisterInfo)}
                                />
                            </Col>
                            <Col span={6}>
                                <div
                                    className={styles.captchaImg}
                                    onClick={captchaClickHandle}
                                    dangerouslySetInnerHTML={{ __html: captcha }}
                                ></div>
                            </Col>
                        </Row>
                    </Form.Item>

                    <Form.Item
                        wrapperCol={{
                            offset: 5,
                            span: 16,
                        }}
                    >
                        <Button
                            type="primary"
                            htmlType="submit"
                            style={{ marginRight: 20 }}
                        >
                            注册
                        </Button>
                        <Button type="primary" htmlType="button" onClick={hanldeReset}>
                            重置
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        )
    }

    return (
        <div>
            <Modal footer={null} title="登录/注册" open={props.isShow} onCancel={handleCancel}>
                <Radio.Group buttonStyle='solid' className={styles.radioGroup} value={value} onChange={onChange}>
                    <Radio.Button value={1} className={styles.radioButton}>登录</Radio.Button>
                    <Radio.Button value={2} className={styles.radioButton}>注册</Radio.Button>
                </Radio.Group>
                {container}
            </Modal>
        </div>
    )
}

export default LoginForm
